package com.zhupanlin.zhyl.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zhupanlin.zhyl.oss.service.FileService;
import com.zhupanlin.zhyl.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/12/3 20:49
 */
@Service
public class FileServiceImpl implements FileService {


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Override
    public String upload(MultipartFile file) {
        String endpoint = ConstantOssPropertiesUtils.ENDPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String secret = ConstantOssPropertiesUtils.SECRET;
        String bucket = ConstantOssPropertiesUtils.BUCKET;

        // 创建 OSS 实例
        OSS ossClint = new OSSClientBuilder().build(endpoint, accessKeyId, secret, bucket);

        // 上传文件流
        InputStream is = null;
        try {
            is = file.getInputStream();
            // 生成随机唯一值，使用 uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("/", "");
            // 按照当前日期，创建文件夹，上传到创建的文件夹
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            String fileName = timeUrl + "" + uuid + file.getOriginalFilename();
            // 调用方法实现上传
            ossClint.putObject(bucket, fileName, is);

            // 上传之后文件的路径
            String url = "https://" + bucket + "." + endpoint+ "/" + fileName;
            return url;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            ossClint.shutdown();
        }


    }
}
